package com.uzai.console.service.wechatprivate.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.common.enums.WxqBlacklistTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.dto.wechatprivate.wxq.wxgroupblacklist.blacklistprv.WxqBlacklistPrvDto;
import com.uzai.console.dto.wechatprivate.wxq.wxgroupblacklist.blacklistprv.WxqBlacklistPrvIdDto;
import com.uzai.console.dto.wechatprivate.wxq.wxgroupblacklist.blacklistprv.WxqBlacklistPrvQuery;
import com.uzai.console.entity.es.WxqBlacklistPrv;
import com.uzai.console.entity.es.WxqBlacklistPub;
import com.uzai.console.service.wechatprivate.WxqBlacklistPrvService;
import com.uzai.console.vo.wechatprivate.wxq.wxgroupblacklist.blacklistprv.WxqBlacklistPrvVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author liuqi
 * @date 2021年08月23日 20:25
 */
@Service
public class WxqBlacklistPrvServiceImpl implements WxqBlacklistPrvService {

    Logger logger = LoggerFactory.getLogger(WxqBlacklistPrvServiceImpl.class);

    @Autowired
    private ElasticsearchUtil elasticsearchUtil;

    /**
     * 查询社群私有黑名单列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqBlacklistPrvQuery
     * @return null
     */
    public Page<WxqBlacklistPrvVo> findWxqBlacklistPrvList(WxqBlacklistPrvQuery wxqBlacklistPrvQuery){
        //新建返回到页面的LIST对象
        List<WxqBlacklistPrvVo> wxqBlacklistPrvVoList = new ArrayList<>();

        //执行分页查询对象
        Page<WxqBlacklistPrvVo> page = new Page<>();
        wxqBlacklistPrvQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        //运营商ID
        boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(wxqBlacklistPrvQuery.getMerId())));

        //黑名单类型(0打广告 1刷屏 2同行 3敏感词 4其他)
        if(wxqBlacklistPrvQuery.getType() != null){
            boolQuery.must(QueryBuilders.termQuery("type", wxqBlacklistPrvQuery.getType()));
        }

        //群微信id
        if(StringUtils.isNotBlank(wxqBlacklistPrvQuery.getGroupWxid())){
            boolQuery.must(QueryBuilders.termQuery("groupWxid", wxqBlacklistPrvQuery.getGroupWxid()));
        }

        //微信id
        if(StringUtils.isNotBlank(wxqBlacklistPrvQuery.getWxid())){
            boolQuery.must(QueryBuilders.termQuery("wxid", wxqBlacklistPrvQuery.getWxid()));
        }

        //微信昵称
        if(StringUtils.isNotBlank(wxqBlacklistPrvQuery.getNick())){
            boolQuery.must(QueryBuilders.matchQuery("nick", wxqBlacklistPrvQuery.getNick()));
        }

        //高亮字段
        String highlightField = null;

        searchSourceBuilder.query(boolQuery);

        //排序
        searchSourceBuilder.sort("createTime", SortOrder.DESC);

        ESResult esResult = elasticsearchUtil.searchListData(EsIndexName.UZAI_WXQ_BLACKLIST_PRV, searchSourceBuilder, wxqBlacklistPrvQuery.getSize(), wxqBlacklistPrvQuery.getFromIndex(), null, null, highlightField, wxqBlacklistPrvQuery.getMerId());
        page.setTotal(esResult.getTotalHits());
        List<Map<String, Object>> dataList = esResult.getDataList();
        if(dataList != null && dataList.size() > 0){
            for (Map<String, Object> dataMp :dataList) {
                WxqBlacklistPrv wxqBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxqBlacklistPrv.class);
                if(wxqBlacklistPrv != null){
                    WxqBlacklistPrvVo wxqBlacklistPrvVo = new WxqBlacklistPrvVo();
                    BeanUtils.copyProperties(wxqBlacklistPrv, wxqBlacklistPrvVo);

                    if(wxqBlacklistPrvVo.getType() != null){
                        WxqBlacklistTypeEnum wxqBlacklistTypeEnum = WxqBlacklistTypeEnum.getById(wxqBlacklistPrvVo.getType());
                        if(wxqBlacklistTypeEnum != null){
                            wxqBlacklistPrvVo.setTypeName(wxqBlacklistTypeEnum.getDesc());
                        }
                    }

                    //查询是否共享黑名单
                    wxqBlacklistPrvVo.setShareStatus(0);  //未共享
                    String wxid = wxqBlacklistPrv.getWxid();
                    if(StringUtils.isNotBlank(wxid)){
                        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB, wxid, null);
                        if(map != null){
                            wxqBlacklistPrvVo.setShareStatus(1);  //已经共享
                        }
                    }

                    wxqBlacklistPrvVoList.add(wxqBlacklistPrvVo);
                }
            }
        }

        //返回到页面分页对象
        page.setRecords(wxqBlacklistPrvVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }

    /**
     * 添加私有黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqBlacklistPrvDto
     * @return null
     */
    @Transactional
    public void addWxqBlacklistPrv(WxqBlacklistPrvDto wxqBlacklistPrvDto){

        if(wxqBlacklistPrvDto.getType() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入黑名单类型");
        }

        if(StringUtils.isBlank(wxqBlacklistPrvDto.getWxid())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入微信id");
        }

        if(StringUtils.isBlank(wxqBlacklistPrvDto.getGroupWxid())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入群微信id");
        }

        //id为merId_wxid
        String id = wxqBlacklistPrvDto.getMerId() + "_" + wxqBlacklistPrvDto.getGroupWxid() + "_" + wxqBlacklistPrvDto.getWxid();
        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PRV, id, null);
        if(map != null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信id已经在此群黑名单中");
        }

        WxqBlacklistPrv wxqBlacklistPrv = new WxqBlacklistPrv();
        BeanUtils.copyProperties(wxqBlacklistPrvDto, wxqBlacklistPrv);

        Integer now = DateUtil.getNowTime();
        wxqBlacklistPrv.setId(id);
        wxqBlacklistPrv.setWxid(wxqBlacklistPrvDto.getWxid());
        wxqBlacklistPrv.setCreateTime(now);
        wxqBlacklistPrv.setUpdateTime(now);

        elasticsearchUtil.addData(wxqBlacklistPrv, EsIndexName.UZAI_WXQ_BLACKLIST_PRV, id);

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    /**
     * 修改私有黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqBlacklistPrvDto
     * @return null
     */
    @Transactional
    public void updateWxqBlacklistPrv(WxqBlacklistPrvDto wxqBlacklistPrvDto){

        if(StringUtils.isBlank(wxqBlacklistPrvDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        if(wxqBlacklistPrvDto.getType() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入黑名单类型");
        }

        if(StringUtils.isBlank(wxqBlacklistPrvDto.getWxid())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入微信id");
        }

        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PRV, wxqBlacklistPrvDto.getId(), null);
        if(map == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该私有黑名单不存在");
        }

        WxqBlacklistPrv wxqBlacklistPrv = new WxqBlacklistPrv();
        BeanUtils.copyProperties(wxqBlacklistPrvDto, wxqBlacklistPrv);
        Integer now = DateUtil.getNowTime();
        wxqBlacklistPrv.setUpdateTime(now);
        wxqBlacklistPrv.setHimg(wxqBlacklistPrvDto.getHimg());
        wxqBlacklistPrv.setType(wxqBlacklistPrvDto.getType());
        wxqBlacklistPrv.setWxid(wxqBlacklistPrvDto.getWxid());

        elasticsearchUtil.updateDataById(wxqBlacklistPrv, EsIndexName.UZAI_WXQ_BLACKLIST_PRV, wxqBlacklistPrvDto.getId());

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    /**
     * 移除黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqBlacklistPrvIdDto
     * @return null
     */
    @Transactional
    public void deleteWxqBlacklistPrv(WxqBlacklistPrvIdDto wxqBlacklistPrvIdDto){

        if(StringUtils.isBlank(wxqBlacklistPrvIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PRV, wxqBlacklistPrvIdDto.getId(), null);
        WxqBlacklistPrv wxqBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqBlacklistPrv.class);
        if(wxqBlacklistPrv == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该私有黑名单不存在");
        }

        //删除私有黑名单
        elasticsearchUtil.deleteDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PRV, wxqBlacklistPrvIdDto.getId());

        //判断是否自己共享了全网黑名单，如果是自己共享的，则同时删除全网黑名单
        if(StringUtils.isNotBlank(wxqBlacklistPrv.getWxid())){
            Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB, wxqBlacklistPrv.getWxid(), null);
            WxqBlacklistPub wxqBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqBlacklistPub.class);
            if(wxqBlacklistPub != null){
                //判断是不是该运营商共享的全网黑名单
                if(wxqBlacklistPub.getMerId().longValue() == wxqBlacklistPrvIdDto.getMerId().longValue()){
                    elasticsearchUtil.deleteDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB, wxqBlacklistPrv.getWxid());
                }
            }
        }

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    /**
     * 查询私有黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqBlacklistPrvIdDto
     * @return null
     */
    public WxqBlacklistPrvVo findWxqBlacklistPrv(WxqBlacklistPrvIdDto wxqBlacklistPrvIdDto){
        if(StringUtils.isBlank(wxqBlacklistPrvIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PRV, wxqBlacklistPrvIdDto.getId(), null);
        if(map == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该私有黑名单不存在");
        }

        WxqBlacklistPrv wxqBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqBlacklistPrv.class);
        WxqBlacklistPrvVo wxqBlacklistPrvVo = new WxqBlacklistPrvVo();
        BeanUtils.copyProperties(wxqBlacklistPrv, wxqBlacklistPrvVo);

        return wxqBlacklistPrvVo;
    }

    /**
     * 共享全网黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqBlacklistPrvIdDto
     * @return null
     */
    public void shareWxqBlacklistPub(WxqBlacklistPrvIdDto wxqBlacklistPrvIdDto){
        if(StringUtils.isBlank(wxqBlacklistPrvIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PRV, wxqBlacklistPrvIdDto.getId(), null);
        WxqBlacklistPrv wxqBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqBlacklistPrv.class);
        if(wxqBlacklistPrv == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该私有黑名单不存在");
        }

        Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB, wxqBlacklistPrv.getWxid(), null);
        WxqBlacklistPub wxqBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqBlacklistPub.class);
        if(wxqBlacklistPub != null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信id已经在共享黑名单里");
        }

        wxqBlacklistPub = new WxqBlacklistPub();
        BeanUtils.copyProperties(wxqBlacklistPrv, wxqBlacklistPub);
        Integer now = DateUtil.getNowTime();
        wxqBlacklistPub.setCreateTime(now);
        wxqBlacklistPub.setUpdateTime(now);
        wxqBlacklistPub.setId(wxqBlacklistPub.getWxid());
        //数据来源(0运营商共享 1官方采集-免费  2收费名单)
        wxqBlacklistPub.setSource(0);
        //增加到全网黑名单
        elasticsearchUtil.addData(wxqBlacklistPub, EsIndexName.UZAI_WXQ_BLACKLIST_PUB, wxqBlacklistPub.getWxid());

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }

    /**
     * 取消全网黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqBlacklistPrvIdDto
     * @return null
     */
    public void cancelWxqBlacklistPub(WxqBlacklistPrvIdDto wxqBlacklistPrvIdDto){
        if(StringUtils.isBlank(wxqBlacklistPrvIdDto.getId())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PRV, wxqBlacklistPrvIdDto.getId(), null);
        WxqBlacklistPrv wxqBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqBlacklistPrv.class);
        if(wxqBlacklistPrv == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该私有黑名单不存在");
        }

        Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB, wxqBlacklistPrv.getWxid(), null);
        WxqBlacklistPub wxqBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqBlacklistPub.class);
        if(wxqBlacklistPub == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信id不在全网黑名单里");
        }

        //判断是不是该运营商共享的全网黑名单
        if(wxqBlacklistPub.getMerId().longValue() != wxqBlacklistPrvIdDto.getMerId().longValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信id是其他运营商共享到全网黑名单");
        }

        elasticsearchUtil.deleteDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB, wxqBlacklistPrv.getWxid());

        try {
            //延迟0.5秒
            Thread.sleep(1000);
        }catch (Exception e){

        }
    }
}
